package com.softeem.servlet;

import com.google.gson.Gson;
import com.softeem.bean.Oss;
import com.softeem.service.OssService;
import com.softeem.service.impl.OssServiceImpl;
import com.softeem.utils.BaseServlet;
import com.softeem.utils.Page;
import com.softeem.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(value="/OssServlet")
public class OssServlet extends BaseServlet {
    protected void searchPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String name = req.getParameter("name");
        String author = req.getParameter("author");
        Double min = WebUtils.parseDouble(req.getParameter("min") , -1);
        Double max = WebUtils.parseDouble(req.getParameter("max") , -1);
        Integer pageNo = WebUtils.parseInt(req.getParameter("pageNo") , 1);
        Integer pageSize = WebUtils.parseInt(req.getParameter("pageSize") , 5);

        OssService ossService = new OssServiceImpl();
        Page<Oss> page = ossService.page(pageNo, pageSize, name, author, min, max);

        Gson gson = new Gson();
        //将page 转换成 json 字符串
        String str = gson.toJson(page);

        resp.setContentType("application/json;charset=utf-8");

        PrintWriter out = resp.getWriter();

        out.print(str);

    }



    protected void getOss(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
        //创建Oss业务层对象
        OssService ossService = new OssServiceImpl();
        //通过request对象获取网页提交上来的id参数.但是它默认是String类型.所以我们将它转换成int类型
        Integer id = WebUtils.parseInt(req.getParameter("id"), 0);
        //调用booService对象中的queryOssById方法.通过id查询出oss对象
        Oss oss = ossService.queryOssById(id);
        //将oss对象保存到request请求域中
        req.setAttribute("oss" , oss);

        // 手动构建JSON字符串
        String jsonResponse = "{" +
                "\"data\": {" +
                "\"id\": " + oss.getId() + "," +
                "\"name\": \"" + oss.getbucketName() + "\"," +
                "\"type\": \"" + oss.gettype() + "\"," +
                "\"permission\": \"" + oss.getpermission() + "\"" +
                // 添加其他需要的字段...
                "}" +
                "}";

        // 输出JSON
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.print(jsonResponse);
        out.flush();
    }


    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
        //创建oss业务层对象 :ossService
        OssService ossService = new OssServiceImpl();

        //调用ossService层中的queryOss方法得到一个ossList集合
        List<Oss> ossList = ossService.queryOss();

        //将ossList集合添加到request请求域中
        req.setAttribute("ossList" , ossList);

        //请求转发到/pages/manager/manager.jsp网页,这样可以将request请求域中的数据传递到jsp网页
        req.getRequestDispatcher("/pages/manager/oss_manager.jsp").forward(req,resp);
    }

    protected void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException,SQLException {
        OssService ossService = new OssServiceImpl();
        req.setCharacterEncoding("UTF-8");
        //判断form表单 是否设置了 enctype="multipart/form-data"
        if(ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类ServletFileUpload 类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            Oss oss = new Oss();
            try {
                int pageNo = 1 ;
                // 解析上传的数据，得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //循环这6段数据并处理它们
                for (FileItem fileItem : list) {
                        if("id".equals(fileItem.getFieldName()) && !fileItem.getString().trim().isEmpty()){
                            oss.setId(Long.valueOf(Integer.valueOf(fileItem.getString())));
                        }
                       if("pageNo".equals(fileItem.getFieldName())){
                            pageNo = WebUtils.parseInt(fileItem.getString() , 1);
                        }else if ("bucketName".equals(fileItem.getFieldName())) {
                            oss.setbucketName(fileItem.getString("utf-8"));
                        } else if ("type".equals(fileItem.getFieldName())) {
                            oss.settype(fileItem.getString("utf-8"));
                        } else if ("capacity".equals(fileItem.getFieldName())) {
                            oss.setcapacity(Long.valueOf(fileItem.getString()));
                        } else if ("flow".equals(fileItem.getFieldName())) {
                            oss.setflow(Long.valueOf(Integer.valueOf(fileItem.getString())));
                        } else if ("visits".equals(fileItem.getFieldName())) {
                            oss.setvisits(Integer.parseInt(fileItem.getString()));
                        }else if ("permission".equals(fileItem.getFieldName())) {
                           oss.setpermission(fileItem.getString("utf-8"));
                       }
                }
                resp.setContentType("application/json;charset=UTF-8");

                String jsonResponse = "{\"success\": \"操作成功\"}";
                try {
                    ossService.saveOrUpdate(oss);
                }catch (Exception e){
                    jsonResponse = "{\"error\": \"名称重复\"}";
                }




                PrintWriter out = resp.getWriter();
                out.print(jsonResponse);
                out.flush();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
        //创建oss业务层对象 :ossService
        OssService ossService = new OssServiceImpl();
        //通过request对象获取网页提交上来的id参数.但是它默认是String类型.所以我们将它转换成int类型
        Integer id =  WebUtils.parseInt(req.getParameter("id") , 0);
        //网页删除的a连接将pageNo提交到了delete方法中.但是delete方法并不需要使用pageNo参数.而是我们的的page方法需要使用pageNo参数
        //Integer pageNo = WebUtils.parseInt(req.getParameter("pageNo") , 1);
        //调用ossService中的deleteossById方法..通过主键id删除数据
        ossService.deleteOssById(id);

    }

    protected void checkNameExists(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {

        String name = req.getParameter("name");
        String id = req.getParameter("id");

        OssService ossService = new OssServiceImpl();
        boolean exists = false;

        if(id != null && !id.isEmpty()) {
            Oss currentOss = ossService.queryOssByName(name);
            if(currentOss != null && currentOss.getbucketName().equals(name)) {
                exists = false;
            } else {
                Oss oss = ossService.queryOssByName(name);
                exists = (oss != null);
            }
        } else {
            Oss oss = ossService.queryOssByName(name);
            exists = (oss != null);
        }

        resp.setContentType("application/json;charset=UTF-8");

        String jsonResponse = "{\"exists\":" + exists + "}";

        PrintWriter out = resp.getWriter();
        out.print(jsonResponse);
        out.flush();
    }

    protected void updatePermissionById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
        String permission = req.getParameter("permission");
        String id = req.getParameter("id");

        OssService ossService = new OssServiceImpl();
        boolean exists = true;

        ossService.updatePermission(Integer.parseInt(id),permission);


        resp.setContentType("application/json;charset=UTF-8");

        String jsonResponse = "{\"success\":" + exists + "}";

        PrintWriter out = resp.getWriter();
        out.print(jsonResponse);
        out.flush();
    }

}
